package com.plpm.service;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.plpm.mapper.FileRecordMapper;
import com.plpm.model.FileRecord;

import lombok.extern.slf4j.Slf4j;

/**
 * 文件清理服务
 * 定期清理失败文件，释放磁盘空间
 *
 * @author PLPM Team
 * @version 1.0
 */
@Slf4j
@Service
public class FileCleanupService {

    @Autowired
    private FileRecordMapper fileRecordMapper;

    @Value("${plpm.file.cleanup.enabled:true}")
    private boolean cleanupEnabled;

    @Value("${plpm.file.cleanup.retention-days:7}")
    private int retentionDays;

    @Value("${file.upload.path}")
    private String uploadPath;

    /**
     * 定时清理失败文件
     * 默认每天凌晨2点执行
     */
    @Scheduled(cron = "${plpm.file.cleanup.cron:0 0 2 * * ?}")
    public void cleanupFailedFiles() {
        if (!cleanupEnabled) {
            log.info("文件清理功能已禁用，跳过清理任务");
            return;
        }

        log.info("开始执行文件清理任务，保留天数: {}", retentionDays);

        try {
            // 计算截止时间（当前时间 - 保留天数）
            LocalDateTime cutoffTime = LocalDateTime.now().minusDays(retentionDays);
            String cutoffTimeStr = cutoffTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            // 查询需要清理的文件记录（syncStatus=2 且创建时间早于截止时间）
            List<FileRecord> failedRecords = fileRecordMapper.selectFailedFilesBeforeTime(cutoffTimeStr);

            if (failedRecords == null || failedRecords.isEmpty()) {
                log.info("未找到需要清理的文件记录");
                return;
            }

            int deletedCount = 0;
            long freedSpace = 0;

            for (FileRecord record : failedRecords) {
                try {
                    String fileName = record.getFileName();
                    if (StringUtils.isNotEmpty(fileName)) {
                        // 构建文件路径：uploadPath + fileName
                        String filePath = uploadPath + fileName;
                        File file = new File(filePath);
                        if (file.exists() && file.isFile()) {
                            long fileSize = file.length();
                            if (file.delete()) {
                                deletedCount++;
                                freedSpace += fileSize;
                                log.debug("删除文件成功: {}, 大小: {} bytes", filePath, fileSize);
                            } else {
                                log.warn("删除文件失败: {}", filePath);
                            }
                        } else {
                            log.debug("文件不存在或不是文件: {}", filePath);
                        }
                    }
                } catch (Exception e) {
                    log.error("清理文件时发生异常，文件名: {}", record.getFileName(), e);
                }
            }

            log.info("文件清理任务完成，删除文件数: {}, 释放空间: {} MB", 
                    deletedCount, freedSpace / 1024 / 1024);

        } catch (Exception e) {
            log.error("文件清理任务执行失败", e);
        }
    }

    /**
     * 手动触发文件清理
     */
    public void cleanupFailedFilesManually() {
        log.info("手动触发文件清理任务");
        cleanupFailedFiles();
    }
}

